package com.woniu34.auth.service;

import com.woniu.common.constant.Constants;
import com.woniu.common.core.redis.RedisCache;
import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import com.woniu34.auth.domain.LoginModel;
import com.woniu34.user.api.UserApi;
import com.woniu34.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService {



    @Autowired
    private UserApi userApi;

    @Autowired
    private RedisCache redisCache;

    public User doLogin(String uuid,String userAccount,String password,String code){
        //获取uuid，检查是否在REDIS中有用户输入的验证码
        String codeKey = Constants.CAPTCHA_CODE_KEY + uuid;
        //从redis中取出验证码
        String codeInRedis = (String)redisCache.getCacheObject(codeKey);
        //比较用户输入的验证码是否等于redis中的验证码
        if( !Objects.equals(code,codeInRedis)){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }

        User user = userApi.findByUserAccountAndPassword(userAccount, password);
        if(user == null){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        //

        return user;

    }

    public User doWebLogin(String userAccount, String password) {
        User user = userApi.findByUserAccountAndPassword(userAccount, password);
        if(user == null){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        Integer userType = user.getUserType();
        if(1==userType){
            throw new CustomException(ExceptionCode.ADMIN_LOGIN_NOT_ALLOWED);
        }

        return user;
    }
}
